package com.ys.cloudpicture.controller;

import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.COSObjectInputStream;
import com.qcloud.cos.utils.IOUtils;
import com.ys.cloudpicture.annotation.AuthCheck;
import com.ys.cloudpicture.common.BaseResponse;
import com.ys.cloudpicture.common.ResultUtils;
import com.ys.cloudpicture.constant.UserConstant;
import com.ys.cloudpicture.exception.BusinessException;
import com.ys.cloudpicture.exception.ErrorCode;
import com.ys.cloudpicture.manager.CosManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("/test")
@Slf4j
public class FileController {
    @Resource
    private CosManager cosManager;

    /**
     * 测试文件上传
     * @param multipartFile
     * @return
     */
    @PostMapping("/upload")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<String> upload(@RequestPart("file")MultipartFile multipartFile) {
        // 获取文件名称
        String filename = multipartFile.getOriginalFilename();
        File file = null;
        // 文件存储路径
        String filePath = "test/" + filename;
        try {
            file = File.createTempFile(filePath, null);
            // 将MultipartFile 转换为File
            multipartFile.transferTo(file);
            cosManager.putObject(filePath, file);
            // 上传成功
            return ResultUtils.success("上传成功："+filePath);
        } catch (Exception e) {
            log.error("上传失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
        } finally {
            // 删除临时文件
            if (file != null) {
                file.delete();
            }
        }
    }

    /**
     * 文件下载
     * @param filePath
     * @param response
     */
    @PostMapping("/download")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public void download(String filePath, HttpServletResponse response) throws IOException {
        COSObjectInputStream cosObjectInput = null;
        try {
            // 获取文件
            COSObject cosObject = cosManager.getObject(filePath);
            cosObjectInput = cosObject.getObjectContent();
            // 将文件内容输出到response的输出流中
            byte[] byteArray = IOUtils.toByteArray(cosObjectInput);
            // 设置响应头
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + filePath);
            // 将文件内容输出到response的输出流中
            response.getOutputStream().write(byteArray);
            response.getOutputStream().flush();
        } catch (Exception e) {
            log.error("下载失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "下载失败");
        } finally {
            if (cosObjectInput != null) {
                cosObjectInput.close();
            }
        }
    }
}
